/*
 * @Descripttion: 
 * @version: 
 * @Author: 高月飞
 * @Date: 2023-11-21 11:53:12
 * @LastEditors: 高月飞
 * @LastEditTime: 2023-11-21 12:40:44
 */

import { ElLoading, ElMessage } from 'element-plus';
import { readFile, utils } from "xlsx";
import type { ICustomerData } from "@/types/customer";
import * as XLSX from 'xlsx';
import { writeFile } from 'xlsx';
import { successMessage } from './successMessage';
import { errorMessage } from './errorMessage';
export const exposeCustomerDate = (value: boolean, exportCustomerTable: any[], CustomHeaders: object) => {
    if (value) {
        const loading = ElLoading.service({
            lock: true,
            text: '数据正在玩命导出生成中...',
            background: 'rgba(0, 0, 0, 0.6)'
        });

        try {
            const customHeaders: any = CustomHeaders

            const exportCustomerData = exportCustomerTable.map((item: typeof exportCustomerTable[0]) => {
                const modifiedItem: any = {};
                for (const key in item) {
                    if (key in customHeaders) {
                        modifiedItem[customHeaders[key]] = item[key];
                    }
                }
                return modifiedItem;
            });

            const sheet = utils.json_to_sheet(exportCustomerData);
            const workerBook = utils.book_new();
            utils.book_append_sheet(workerBook, sheet, 'Customer records');
            writeFile(workerBook, 'Customer records.xlsx');

            successMessage('导出用户记录成功', () => {
                loading.close();
            }, 3000);
        } catch (err) {
            errorMessage('导出用户记录失败，请重新选中导出', () => {
                loading.close();
            }, 3000);
        }
    }
};
